<!--
 * @Author: 刘金开 liujinkai@jiankeyan.com
 * @Date: 2023-07-11 22:44:11
 * @LastEditors: 刘金开 liujinkai@jiankeyan.com
 * @LastEditTime: 2023-08-07 11:47:06
 * @FilePath: \font\src\view\class.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
	<div  class="container">
		<el-card >
				<div class="title" >
            <div class="mt-4" style=" display: inline-block;">
            <el-input v-model="input3" placeholder="请输入学生姓名进行查询" :clearable="true"  class="input-with-select" style="width: 500px; "
                  size="large">
              <!-- <template #prepend>
              <el-select v-model="select" placeholder="请选择专业" size="large" clearable="true" style="width: 120px">

                <el-option v-for="(item, index) in filteredArray" :key="index" :label="item.label" :value="item.value"></el-option>
              </el-select>
              </template> -->
              <template #append>
              <el-button  type="primary" text @click="searchFor">

                <el-icon><Search /></el-icon>
                </el-button>
              <!-- <el-button class="button" size="large" text >Operation button</el-button> -->
              </template>
            </el-input>
            </div>
            <div style=" display: inline-block;">
            <!-- <el-button type="primary" class="button"  size="large" text @click="getSpecialList">全部</el-button> -->

            <el-button text type="primary" size="large" @click="addStudentClick">添加博雅学子</el-button>

            <el-button text type="primary" size="large" @click="manyDelClick(arr)">批量删除</el-button>


                  <el-button  class="iconBox" type="primary" text @click="refresh">
                <el-icon class="hoverIcon"><RefreshRight /></el-icon>
                </el-button>
                <el-button text type="primary" size="large" @click="exportDownloadClick">导出下载</el-button>
            </div>
	  </div>
	<!-- 表格 -->

    <el-table
    id="tableId"
    :border="true"
  :data="dataList"
  :max-height="maxHeight"
 :highlight-current-row="true"
 :row-style="{height: '15px'}"
  @selection-change="selectionChange"
 >
 <el-table-column type="selection" width="35" />
  <el-table-column type="index" width="50"   align="center"  />
  <el-table-column fixed prop="id" label="学生id" width="50" v-if="false" />
    <el-table-column prop="name" label="姓名" width="100"  align="center" :show-overflow-tooltip="true"/>
    <el-table-column prop="sex" label="性别" width="60"  align="center" />
    <el-table-column prop="age" label="年龄" width="60"  align="center" />
    <el-table-column prop="telephone" label="家长电话"  align="center" width="120" :show-overflow-tooltip="true"/>
    <el-table-column prop="school" label="学校" width="100"  align="center" :show-overflow-tooltip="true" />
    <el-table-column prop="created_at" label="创建时间"  align="center" width="120" />
    <el-table-column prop="updated_at" label="更新时间"  align="center" width="120" />
    <el-table-column prop="status" header-align="center"  label="是否在读"   align="center" width="100">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.status === false">否</el-tag>
            <el-tag type="success" v-else-if="scope.row.status === true">是</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="note" label="备注"  align="center" width="319"   :show-overflow-tooltip="true"/>
    <el-table-column fixed="right" label="操作" width="120"  align="center" >
      <template   #default="scope">
        <el-button link type="primary" size="small" @click="editClick(scope)"
          >编辑</el-button
        >
        <el-button link type="danger" size="small" @click="handleDelete(scope.$index,scope)">删除</el-button>
      </template>
    </el-table-column>
    </el-table>


        <!-- 分页器 -->
        <div class="pageNation">
            <pagination
            :pageSize="pageResult.pageSize"
          :layout="layout"
          :pageTotal="allPages"
            @pageFunc="pageFunc">
          </pagination>
          </div>
		</el-card>

      <!-- el-dialog 新增-->
      <el-dialog
  v-model="showAddPage"
  title="添加学生信息"
  :modal="false"
  width="60%"
   center>

   <el-form
   ref="ruleForms"
    :model="ruleForm"
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
    :inline="true"
    status-icon
  >
    <el-form-item label="姓名"  prop="name" >
      <el-input v-model="ruleForm.name"  placeholder="请输入专业名称 " />
    </el-form-item>
    <el-form-item label="性别"  prop="sex" >
      <el-input v-model="ruleForm.sex"  placeholder="请输入性别 " />
    </el-form-item>
    <el-form-item label="年龄"  prop="age" >
      <el-input v-model.number="ruleForm.age" placeholder="请输入年龄 " />
    </el-form-item>
    <el-form-item label="学校"  prop="school" >
      <el-input v-model="ruleForm.school"  placeholder="请输入学校 " />
    </el-form-item>
    <el-form-item label="家长电话"  prop="telephone" >
      <el-input v-model.number="ruleForm.telephone"  placeholder="请输入家长电话" />
    </el-form-item>
    <el-form-item label="是否在读" prop="status">
      <el-radio-group v-model="ruleForm.status">
        <el-radio :label="true" border >是</el-radio>
      <el-radio :label="false" border>否</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="备注"  prop="note"  >
    <el-input v-model="ruleForm.note" style="width: 600px;"   placeholder="可在此处添加备注信息哦"  />
     </el-form-item>








 <el-row type="flex" justify="center">

    <el-form-item >
        <el-button @click="showAddPage=false">取消</el-button>
      <el-button type="primary" @click="submitForm()">
        确认
      </el-button>

    </el-form-item>
 </el-row>
  </el-form>



  </el-dialog>

<!-- 编辑 -->
<el-dialog
  v-model="showEditPage"
  title="编辑学生信息"
  :modal="false"
  width="60%"
   center>

   <el-form
   ref="ruleForms"
    :model="editForm"
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
    :inline="true"
    status-icon
  >
  <el-form-item label="姓名"  prop="name" >
      <el-input v-model="editForm.name"  placeholder="请输入专业名称 " />
    </el-form-item>
    <el-form-item label="性别"  prop="sex" >
      <el-input v-model="editForm.sex"  placeholder="请输入性别 " />
    </el-form-item>
    <el-form-item label="年龄"  prop="age" >
      <el-input v-model.number="editForm.age" placeholder="请输入年龄 " />
    </el-form-item>
    <el-form-item label="学校"  prop="school" >
      <el-input v-model="editForm.school"  placeholder="请输入学校 " />
    </el-form-item>
    <el-form-item label="家长电话"  prop="telephone" >
      <el-input v-model.number="editForm.telephone"  placeholder="请输入家长电话" />
    </el-form-item>
    <el-form-item label="是否在读" prop="status">
      <el-radio-group v-model="editForm.status">
        <el-radio :label="true" border >是</el-radio>
      <el-radio :label="false" border>否</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="备注"  prop="note"  >
    <el-input v-model="editForm.note" style="width: 600px;"   placeholder="可在此处添加备注信息哦"  />
     </el-form-item>





 <el-row type="flex" justify="center">

    <el-form-item >
        <el-button @click="showEditPage=false">取消</el-button>
      <el-button type="primary" @click="submitEditForm()">
        确认
      </el-button>

    </el-form-item>
 </el-row>
  </el-form>



  </el-dialog>

	</div>
</template>

<script setup>

 import {getStudent,createStudent,editStudent,deleteStudent,getStudentAll} from "../services/api/student.js";
 import {onMounted, reactive, ref, computed, toRaw, nextTick, watch, onBeforeMount, toRefs, onBeforeUnmount} from "vue";
import {ElMessageBox, ElNotification } from 'element-plus'
import pagination from '../components/pageNation.vue'
import{ exportDownload}from '../utils/exportExcel'
import {  useRoute} from 'vue-router';
import {
    Message,
    Setting,
    Document,
    Memo,
    Reading,
    Star,
    User,
    Postcard,
    School,
    List,
    ElementPlus,
    Flag,
    Ticket,
    Platform,
    Expand, Fold,
    Search,
    RefreshRight
} from '@element-plus/icons-vue';
let layout = "total,sizes, prev, pager, next, ->,jumper, slot";
const list = ref()
const input3=ref('');
const dataList = ref([]);
const allPages=ref()
const showAddPage=ref(false);
const ruleForms = ref(null);
const arr = ref([]);
const arrs = ref([]);
// const select=ref(0)
const showEditPage=ref(false)
const pageResult = reactive({
        // 放置页码及相关数据
        page: 1, //当前页
        pageSize: 20, //每页条目数
        // name:'',
      });

// 获取所有的专业id和名字所传参数
// const specialIdAll = reactive({
//         // 放置页码及相关数据
//         page: 1, //当前页
//         pageSize: 100, //每页条目数
//       });
// 编辑表单绑定数据
      const editForm=reactive({
          id:'',
          name: '刘',
          age: '',
          school: '',
          sex:'',
          telephone: '',
          status:false ,
          note:''
        })
// 导出表格名称
const excelName=ref('学生信息')
// const List=ref()

// const filteredArray=ref()
      // 表单验证
const rules = reactive({
          name: [
            { required: true, message: '请输入学生姓名', trigger: 'blur' },
            { min: 2, max: 10, message: '长度2到10个字符', trigger: 'blur' },
          ],
          sex: [
            { required: true, message: '请输入学生性别', trigger: 'blur' },
            { min: 1, max: 2, message: '长度1到2个字符', trigger: 'blur' },
          ],
          age: [
          {
            type: "number",
            required: true,
            message: "请输入学生年龄",
            trigger: "blur",
          },
        ],
        telephone: [
          {
            type: "number",
            message: "请输入家长手机号码",
            trigger: "blur",
          },
        ],
        school: [
            { required: true, message: '请输入学生所在学校', trigger: 'blur' },
            { min: 2, max: 20, message: '长度2到20个字符', trigger: 'blur' },
          ],
          status: [
            {
              required: true,
              message: 'Please pick a option',
              trigger: 'change',
            },
          ],
          note: [
            {
              message: 'Please select activity resource',
              trigger: 'blur',
            },
          ],


        })
// 新增学生     表单绑定数据
  const ruleForm = reactive({

          name: '',
          age: '',
          school: '',
          sex:'',
          telephone: '',
          status:false ,
          note:'',
        })
//  编辑学生
      const editClick = (scope) => {
       showEditPage.value=true
        // Object.assign(editForm,scope.row)
        editForm.name= scope.row.name
        editForm.note= scope.row.note
         editForm.age= scope.row.age
         editForm.id= scope.row.id
         editForm.sex =scope.row.sex
         editForm.telephone =scope.row.telephone
         editForm.school =scope.row.school
        if(scope.row.status==true){
          editForm.status= true
        }else{
          editForm.status= false
        }

      };

// 编辑确定
   const submitEditForm=()=>{

    editForm.telephone= editForm.telephone.toString()
    editStudent(editForm).then((res)=>{

          showEditPage.value=false
          if(res.data.msg=='OK'){
            getStudentList()
            ElNotification({
                                    title: 'Success',
                                    message: '编辑学生信息成功',
                                    type: 'success',
                                      })
          }else{
            ElNotification({
                                      title: 'Error',
                                      message: '编辑学生信息失败',
                                      type: 'error',
                          })
          }
        })


      }
//   // 新增弹窗控制按钮
 const addStudentClick = () => {
        showAddPage.value=true

      };
// 获取学生列表接口调用
const getStudentList=async () => {
        const res = await getStudent(pageResult)
        dataList.value = res.data.data.studentData;
        allPages.value= res.data.data.count

      };
// // 右上角刷新
const refresh=()=>{
  input3.value=''
    getStudentList();

}
// 新增学生
     const submitForm= ()=>{
        ruleForms.value.validate((valid) => {
        if (valid) {
            ruleForm.telephone= ruleForm.telephone.toString()
            createStudent(ruleForm).then((res)=>{
            const { name } = toRefs(ruleForm);
                              if(res.data.code === 200){
                                  showAddPage.value=false
                                  getStudentList();
                                  nextTick(() => {
                                      ruleForms.value.resetFields();
                                                  });
                                  ElNotification({
                                    title: 'Success',
                                    message: `添加学生--${name.value}成功`,
                                    type: 'success',
                                      })
                                      getClassList();
                        }else{
                                    ElNotification({
                                      title: 'Error',
                                      message: `添加学生--${name.value}失败`,
                                      type: 'error',
                          })
                        }
                  })

        }})

      }
// // 获取专业id和名称
//       const getSpecialList = async () => {
//         const res = await getSpecialAll(specialIdAll)
//         list.value = res.data.data.specialities;
//         filteredArray.value = list.value.map(obj => ({ value: obj.id, label: obj.name }));
//         filteredArray.value.unshift({value: 0,label:'班级查询' });
//       };
// 单个删除学生
    //  const handleDelete  = (index,scope) => {
    //    let id=scope.row.id
    //    let studentName=scope.row.name
    //    arr.value=[]
    //     arr.value=[...arr.value,id]
    //     deleteStudent(arr.value).then((res)=>{
    //         if(res.data.msg=='OK'){
    //          dataList.value.splice(index, 1)
    //          arr.value=[]
    //          getStudentList();
    //          ElNotification({
    //                                 title: 'Success',
    //                                 message: `成功删除--${studentName}信息`,
    //                                 type: 'success',
    //                                   })
    //         }else{
    //         ElNotification({
    //                                   title: 'Error',
    //                                   message: `删除--${studentName}信息失败`,
    //                                   type: 'error',
    //                       })
    //       }

    //     })



    //   }
      const handleDelete = (index,scope) =>{
            ElMessageBox.confirm(
                `确认删除?  >>> ${scope.row.name}`,
                'Warning',
                {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(() => {
                  let id=scope.row.id
       let studentName=scope.row.name
       arr.value=[]
        arr.value=[...arr.value,id]
        deleteStudent(arr.value).then((res)=>{
            if(res.data.msg=='OK'){
             dataList.value.splice(index, 1)
             arr.value=[]
             getStudentList();
             ElNotification({
                                    title: 'Success',
                                    message: `成功删除--${studentName}学生信息`,
                                    type: 'success',
                                      })
            }else if(res.data.msg=='数据存在被引用'){
            ElNotification({
                                      title: 'Error',
                                      message: `${studentName}已参与排课，删除失败`,
                                      type: 'error',
                          })
          }else if(res.data.msg=='数据删除错误'){
            ElNotification({
                                      title: 'Error',
                                      message: `${studentName}信息删除失败，请检查网络`,
                                      type: 'error',
                          })
          }else if(res.data.msg=='数据绑定错误'){
            ElNotification({
                                      title: 'Error',
                                      message: `${studentName}绑定错误删除失败`,
                                      type: 'error',
                          })
          }

        })


                })
                .catch(() => {
                    ElNotification({
                        title: '撤销删除',
                        type: 'info',
                        message: 'deleted canceled',
                    })
                })
        }
// 批量删除拿到id
    const selectionChange=(selection)=>{
                arrs.value=[]
                let params = JSON.parse(JSON.stringify(selection));
                        for( let i=0;i<params.length;i++ ){
                          arrs.value.push(params[i].id)
                        }
                        arr.value = [...new Set(arrs.value)];
      }
//  批量删除学生
          const manyDelClick=(val)=>{
            deleteStudent(val).then((res)=>{
            if(res.data.msg=='OK'){
                getStudentList();
             arrs.value=[]
             ElNotification({
                                    title: 'Success',
                                    message: '批量删除成功',
                                    type: 'success',
                                      })
            }

        })
      }
         // 查询
const searchFor=()=>{
        let params={
          page:1,
          pageSize:5,
          name:input3.value,
        }
         getStudentAll(params).then((res)=>{
          dataList.value = res.data.data.studentData;
          allPages.value= res.data.data.count
        })

      }

// 导出下载
const exportDownloadClick=( ()=>{
  pageResult.pageSize = allPages.value;
  getStudent(pageResult).then( async(res)=>{
  dataList.value = res.data.data.studentData;
  nextTick(() => {
    exportDownload(excelName.value,)
  });
})
})

watch(input3, (newValue) => {
      if (newValue === '') {
        getStudentList();
      }
    });

    watch(dataList, (newArr) => {
  newArr.forEach((obj) => {
    obj.created_at = obj.created_at.slice(0, 10);
    obj.updated_at = obj.updated_at.slice(0, 10);
    // obj.classTimeStart = obj.classTimeStart.slice(11, 19);
    // obj.classTimeEnd = obj.classTimeEnd.slice(11, 19);
  });
});

// 分页函数
const pageFunc = (data) => {
        pageResult.pageSize = data.pageSize;
        pageResult.page = data.pageNum;
        getStudentList();  // 触发获取数据函数
      };
      const route = useRoute();

      const remValue = 15.5; // 替换成你需要的 REM 值

const maxHeight = computed(() => {
  const bodyHeight = document.body.clientHeight;
  return `calc(${bodyHeight}px - ${remValue}rem)`;
});

 const handleWindowResize = () => {
     location.reload();
     console.log('窗口发生改变');
 };

 onMounted(() => {
     // 添加窗口尺寸变化事件监听
     window.addEventListener('resize', handleWindowResize);
 });

 onBeforeUnmount(() => {
     // 移除窗口尺寸变化事件监听
     window.removeEventListener('resize', handleWindowResize);
 });
onBeforeMount(()=>{

    getStudentList();
    showAddPage.value=route.query.showAddPage
})
// 	  onMounted(()=>{
//     getSpecialList()
// })
</script>
<style scoped>
.el-card{
    height: 90vh;
}
svg {
  width: 20px;
  height: 20px;

}
.iconBox{
  position: fixed;
  right: 10px;

}


</style>
